<template>
  <div>
    <!-- ====================== 分类参数 ==================== -->
    <!-- 面包屑 -->
    <MBX level1="商品管理" level2="分类参数"></MBX>

    <!-- 卡片主体 -->
    <el-card class="mt16">
      <!-- 警告 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        :closable="false"
        type="warning"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类 -->
      <el-row class="mt16">
        <el-col :span="4" :offset="0">
          <p class="demonstration">选择商品分类</p>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- 级联选择器  -->
          <el-cascader
            v-model="checkedArr"
            :options="goodsCateData"
            :props="defaultProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 商品分类参数列表 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮 -->
          <el-row>
            <el-col>
              <el-button
                size="mini"
                :disabled="isOk"
                type="primary"
                @click="add"
                >添加参数</el-button
              >
            </el-col>
          </el-row>

          <!-- 参数列表渲染区 -->
          <!-- 动态区域 -->
          <el-table class="mt16" :data="manyParams" border style="width: 100%">
            <el-table-column type="expand" label="#">
              <template slot-scope="scope">
                <div>
                  <!-- 渲染出来的tag标签 -->
                  <!-- <el-tag
                    :key="index"
                    v-for="(item, index) in scope.row.attr_vals"
                    >{{ item }}
                  </el-tag> -->

                  <!-- 添加新的tag标签 -->
                  <el-tag
                    :key="index"
                    v-for="(item, index) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(scope.row, item)"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                  <!-- 添加新标签结束 -->
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <!-- 俩按钮 -->
              <template slot-scope="scope">
                <div>
                  <!-- 编辑 -->
                  <el-button
                    type="primary"
                    :disabled="false"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editBtn(scope.row)"
                    >编辑</el-button
                  >
                  <!-- 删除 -->
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="del(scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <!-- ========================= -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加按钮 -->
          <el-row>
            <el-col>
              <el-button
                size="mini"
                :disabled="isOk"
                type="primary"
                @click="add"
                >添加参数</el-button
              >
            </el-col>
          </el-row>

          <!-- 参数列表渲染区 -->
          <!-- 静态区域 -->
          <el-table
            class="mt16"
            :data="onlyParamArr"
            border
            style="width: 100%"
          >
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <!-- 俩按钮 -->
              <template slot-scope="scope">
                <div>
                  <!-- 编辑 -->
                  <el-button
                    type="primary"
                    :disabled="false"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editBtn(scope.row)"
                    >编辑</el-button
                  >
                  <!-- 删除 -->
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="del(scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table> </el-tab-pane
        ><!-- =========================== -->
      </el-tabs>
    </el-card>

    <!-- -- 添加用户对话框 弹出框  -->
    <el-dialog title="添加参数" :visible.sync="addBox">
      <p>参数名称：</p>
      <el-input class="addInput" v-model="input"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addBox = false">取 消</el-button>
        <el-button type="primary" @click="yesAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- -- 编辑用户对话框 弹出框  -->
    <el-dialog title="修改动态参数" :visible.sync="editBox">
      参数名称：<br />
      <el-input class="addInput mt16" v-model="editInput"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editBox = false">取 消</el-button>
        <el-button type="primary" @click="editOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      editInput: "", // 编辑的输入框
      editBox: false, // 编辑的弹出框的状态
      input: "", // 添加的输入框
      addBox: false, // 添加的弹出框的状态
      inputVisible: false, // tag标签的input变成输入框的状态，默认false隐藏
      // inputValue: "", //tag标签的input输入框的内容
      only: "", //静态属性
      activeName: "many", // 默认的动态参数
      // 三级商品分类配置项
      defaultProps: {
        expandTrigger: "hover",
        children: "children",
        label: "cat_name",
        value: "cat_id",
      },
      checkedArr: [], // 三级分类  存放选中分类id组成的数组
      goodsCateData: [], // 三级分类 数据源
      manyParams: [], // 动态参数数组
      onlyParamArr: [], // 静态参数数组
      editVal: "",
    };
  },
  methods: {
    // 点击【编辑】按钮，出现弹框
    editBtn(row) {
      // console.log("选中编辑的那一行的::", row);
      this.editInput = row.attr_name;
      this.editBox = true;
      this.editVal = row;
      // console.log(this.editInput);
      // console.log(this.editBox);
      // console.log(this.editVal);
    },
    //点击确定，[编辑]更新到后台，视图刷新
    async editOk() {
      const obj = {
        attr_name: this.editInput,
        attr_sel: this.activeName,
        attr_vals: this.editVal.attr_vals,
      };

      // 编辑，判断一下，如果tab属性是动态的时候
      if (this.activeName === "many") {
        obj.attr_vals = this.editVal.attr_vals.join(","); //更改好的，让他等于他原数组里面的这个参数，不能等于‘’，否则会被清空
      }

      // console.log(obj);
      const res = await this.$API.editGoodsParamsApi(
        this.current_cate_id,
        this.editVal.attr_id,
        obj
      );
      // console.log("编辑的", res);
      this.editBox = false;
      this.editInput = "";
      this.getGoodsParamsList();
    },

    // 点击删除
    del(row) {
      // console.log("要删除的一行：161：：：", row);
      this.$confirm("是否要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$API.delGoodsParamsApi(
            this.current_cate_id,
            row.attr_id
          );
          // console.log("删除：", res);
          this.getGoodsParamsList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击添加按钮，出现弹框
    add() {
      this.input = ""; // 点开输入框的时候，让他先=空
      this.addBox = true;
    },
    // 点击确定，更新到后台，视图刷新
    async yesAdd() {
      const obj = {
        attr_name: this.input,
        attr_sel: this.activeName,
        attr_vals: "",
      };
      if (this.activeName === "many") {
        obj.attr_vals = "";
      }
      const res = await this.$API.addGoodsParamsApi(this.current_cate_id, obj);
      // console.log("添加", res);
      this.addBox = false;
      this.getGoodsParamsList();
    },
    //点击tag按钮的时候切换成input时触发
    showInput(row) {
      // console.log('选中添加的那一行的tag::',row);
      // row.inputValue = "";
      // row.inputVisible = true; //点击tag按钮的时候，true出现input

      // this.$nextTick((_) => {
      //   this.$refs.saveTagInput.$refs.input.focus();
      // });
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // tag回车，或者失焦时触发
    async handleInputConfirm(row) {
      // console.log("触发了tag回车和失焦时间");
      // console.log(" tag回车添加上的：：", row);
      const inputValue = row.inputValue;
      if (inputValue) {
        row.attr_vals.push(row.inputValue);
        const res = await this.$API.editGoodsParamsApi(
          this.current_cate_id,
          row.attr_id,
          {
            attr_name: row.attr_name,
            attr_sel: this.activeName,
            attr_vals: row.attr_vals.join(","),
          }
        );
      }
      row.inputVisible = false; // 离开tag的时候。失焦，变成false消失
      row.inputValue = "";
    },
    // 删除tag标签时触发
    async handleClose(row, item) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1);
      const obj = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(","),
      };
      const res = await this.$API.editGoodsParamsApi(
        row.cat_id,
        row.attr_id,
        obj
      );
    },
    // 获取商品参数列表
    async getGoodsParamsList() {
      // console.log("商品参数列表");
      if (this.checkedArr.length !== 3) {
        // 错误提示
        this.$message({
          type: "error",
          message: "您需要选择三级分类，才能添加或者编辑参数",
        });

        this.manyParams = [];
        this.onlyParamArr = [];

        // 直接返回
        return false;
      }
      // 调取参数获取接口
      const res = await this.$API.getGoodsParamsApi(
        this.current_cate_id,
        this.activeName
      );
      // console.log(`当前${this.activeName}下的分类参数--124`, res);

      // 区分动态 静态 参数渲染，
      if (this.activeName === "many") {
        // 渲染动态参数
        res.forEach((item) => {
          //区分tag的不同，点击那个改那个
          item.inputVisible = false;
          item.inputValue = "";
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });

        // 渲染动态参数
        // console.log("动态：：：：", res);
        this.manyParams = res;
      } else if (this.activeName === "only") {
        // 渲染静态参数
        this.onlyParamArr = res;
      }
    },
    // 点击动态的参数列表 动态静态 tab 切换时触发
    handleClick() {
      // console.log(this.activeName);
      this.getGoodsParamsList();
    },

    // 三级分类 点击选择数据时触发
    handleChange() {
      this.getGoodsParamsList();
    },

    // 调用商品分类的数据接口
    async getGoodsCateList() {
      const res = await this.$API.getGoodsCateListApi();
      // console.log("三级分类 级联框 分类数据：：", res);
      this.goodsCateData = res;
    },
  },
  created() {
    // 调用列表数据
    this.getGoodsCateList();
  },
  computed: {
    // 取值 取最后一位
    current_cate_id() {
      return this.checkedArr[this.checkedArr.length - 1];
    },
    // 判断添加按钮是否禁用
    isOk() {
      // 当不等于三时，禁用。否则启用
      return this.checkedArr.length !== 3;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 6px 10px;
}
.el-input {
  width: 100px;
}
// 添加的input
.addInput {
  width: 100%;
}

// 弹出框
.el-dialog {
  padding: 20px;
}
</style>
